<!--
 * @Author: xuna
 * @Descripttion:  上传活动头图
-->
<template>
  <div>
    <div class="upload-img">
      <div v-show="imgPath" class="img-con">
        <img
          v-if="!isDisable"
          src="@/assets/img/icon_delete_x.png"
          class="delete-icon"
          @click="deleteImg"
        />
        <img class="show-img" :src="imgPath" />
      </div>
      <div v-if="!imgPath" class="btn-upload" @click="doUpload">
        <span>+</span>
      </div>
      <input v-show="false" ref="uploadWidget" type="file" @change="handleImage" />
      <p v-if="imgPath" class="tip" @click="doUpload">重新上传</p>
      <p>图片说明</p>
      <p>
        1. 图片尺寸建议654*296px，jpg或png格式，不超过5M
      </p>
      <p>2.上传精美的头图，更具吸引力</p>
    </div>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex';
  import { batchUploadImage } from '@/api/noticeinformation';
  export default {
    props: {
      picturePath: {
        type: String,
        required: true,
      },
      isDisable: {
        type: Boolean,
        required: true,
      },
    },
    data() {
      return {
        imgPath: '',
      };
    },
    computed: {
      ...mapGetters('user', ['userInfo']),
      isClient() {
        return !!this.userInfo.isClient || false;
      },
    },
    watch: {
      picturePath(val) {
        // if (val) {
        this.imgPath = val;
        // }
      },
    },
    activated() {},
    methods: {
      deleteImg() {
        this.imgPath = '';
      },
      doUpload() {
        if (this.isDisable) return;
        this.$refs.uploadWidget.click();
      },
      handleImage() {
        const _this = event.target;
        const file = _this.files[0];
        console.log(file, '-----------');
        if (!/(jpg|png|jpeg)$/.test(file.name.toLowerCase())) {
          this.$message.error('请上传jpg或png格式的图片');
          _this.value = '';
          return;
        }
        if (file.size > 5 * 1024 * 1024) {
          this.$message.error('上传图片不能大于5M');
          _this.value = '';
          return;
        }
        const fileReader = new FileReader();
        fileReader.readAsDataURL(file);
        fileReader.onload = e => {
          var data = e.target.result;
          //加载图片获取图片真实宽度和高度
          var image = new Image();
          image.src = data;
          image.onload = async () => {
            var width = image.width;
            var height = image.height;
            console.log(width, height); //图片真实宽高
            // if (width != 654 || height != 296) {
            //   return this.$message.error('请上传尺寸为654*296的图片');
            // }
            // const blob = this.dataURLtoBlob(e.target.result);
            let _flie = file;
            if (this.isClient) {
              const { electronReadFile } = require('@/utils/electronUpload');
              _flie = await electronReadFile(_flie.path);
            }
            let formData = new FormData();
            formData.append('files', _flie);
            try {
              batchUploadImage(formData).then(res => {
                if (res.status == 200) {
                  console.log(res);
                  this.imgPath = res.data[0].filePath;
                  this.$refs.uploadWidget.value = '';
                  this.$emit('getImgPath', this.imgPath);
                } else {
                  this.$refs.uploadWidget.value = '';
                  return this.$message.error('上传失败！');
                }
              });
            } catch (error) {
              this.$refs.uploadWidget.value = '';
            }
          };
        };
      },
      dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
      },
    },
  };
</script>

<style lang="scss" scoped>
  @import '~@/styles/mixin.scss';
  .upload-img {
    p {
      @include font(14px, #7f848b, 400);
      margin: 0;
      padding: 0;
      line-height: 26px;
      &.tip {
        @include font(14px, #3770eb, 800);
        margin-top: 12px;
      }
    }
  }
  .img-con {
    position: relative;
    @include wh(262px, 118px);
    margin-bottom: 16px;
    .show-img {
      @include wh(100%, 100%);
      border-radius: 7px;
    }
    .delete-icon {
      @include wh(16px, 16px);
      position: absolute;
      top: -8px;
      right: -8px;
    }
  }
  .btn-upload {
    @include wh(262px, 118px);
    background-color: #f3f3f3;
    border-radius: 7px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 16px;
    span {
      @include font(14px, #ccc, 400);
    }
  }
</style>
